package utils

import (
	"fmt"
	"time"
)

type accessRecord struct {
	time  time.Time
	count int
}

// 桶
type LeakBucket struct {
	capacity       int           // 容量，固定时间语序访问次数
	interval       time.Duration // 允许访问的时间间隔
	dropsNum       int           // 固定时间访问了多少次
	lastAccessTime time.Time     // 最近一次的访问时间
	records        []*accessRecord
}

func NewLeakBucket(capacity int) *LeakBucket {
	bucket := &LeakBucket{
		capacity: capacity,
		interval: time.Second,
	}
	return bucket
}

func (b *LeakBucket) AccessControl() bool {
	fmt.Println("开始")
	now := time.Now()

	// 移除超过指定时间的访问记录
	for len(b.records) > 0 && now.Sub(b.records[0].time) > b.interval {
		b.dropsNum -= b.records[0].count
		b.records = b.records[1:]
	}

	if b.dropsNum >= b.capacity {
		fmt.Println("结束失败")
		return false
	}

	b.dropsNum++
	b.lastAccessTime = now

	// 更新最后一次访问的记录
	if len(b.records) == 0 || now.Sub(b.records[len(b.records)-1].time) > b.interval {
		// 如果访问时间间隔超过指定时间，则添加新的访问记录
		b.records = append(b.records, &accessRecord{
			time:  now,
			count: 1,
		})
	} else {
		// 否则，更新最后一次访问记录的访问次数
		b.records[len(b.records)-1].count++
	}
	fmt.Println("结束成功")
	return true

}
